package com.wkr.springbootquartz.manager;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.function.Consumer;

/**
 * @author: wukangrong
 * @date: 2020/6/30 13:37
 * @description:
 */
@Service
@Slf4j
public class QuartzManager {

    @Autowired
    private Scheduler scheduler;


    public void addJob(Job job, String jobName, String groupName, String cronExpression) {
        try {

            JobDetail jobDetail = JobBuilder.newJob(job.getClass()).withIdentity(jobName, groupName).build();

            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).startNow().build();
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
//            scheduler.
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
                log.info("开始{}.{}任务", groupName, jobName);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
    public void updatCronExpression(String jobName, String groupName, String cronExpression) {
        TriggerKey triggerKey = new TriggerKey(jobName, groupName);

        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).startNow().build();
        try {
            scheduler.rescheduleJob(triggerKey, trigger);
            log.info("{} {} 任务cron重置为 {}", groupName, jobName, cronExpression);
        } catch (SchedulerException e) {
            log.error("重置cron异常", e);
        }
    }

//    public void updateSchduleJob(Task entity){
//
//        TriggerKey triggerKey = new TriggerKey(entity.getId()+"");
//        CronTriggerImpl trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);
//
////        if (trigger == null) {
////            addSchduleJob(entity);
////        } else {
////            trigger.setCronExpression(entity.getTitle());
////            scheduler.rescheduleJob(triggerKey, trigger);
////        }
//    }

    public void queryJobs() throws SchedulerException {
        Set<JobKey> jobKeySet = scheduler.getJobKeys(GroupMatcher.anyGroup());

        log.info(jobKeySet.toString());
    }

    public void pauseJobs(String jobName, String groupName){
        JobKey job = JobKey.jobKey(jobName, groupName);
        try {
            if (scheduler.checkExists(job)) {
                scheduler.pauseJob(job);
                log.info("暂停{}.{}任务", groupName, jobName);
            }
        } catch (SchedulerException e) {
            log.error("暂停任务异常", e);
        }
    }

}
